#!usr/bin/env python
# -*- coding:utf-8 -*-
# user nanme: Mr.zhang
# data time : 2022/8/18   6:36 下午
# project   : read_ip.py
# IDE       : PyCharm
# email     :17600960626@163.com

import logging
import re
import subprocess
from lib.read_sql import db


def ip_list(devices):
    # 获取连接设备ip
    ip_list =[]
    for i in devices:
        sql = 'INSERT IGNORE INTO ip_tab(devices) values ("%s")'%i
        db.insertDB(sql)
        ip_adb = 'adb -s %s shell ip addr show wlan0'%i
        ip_name=subprocess.getoutput(ip_adb)
        a=ip_name.strip().split('\n')
        for j in a[:3]:
            if 'inet' in j:
                s=j.split()[1]
                ip = re.findall(r'^(.*?)\/',s)
                ip_list.append(ip[0])
    #更新已连接设备ip
    try:
        for i,j in zip(ip_list,devices):
            sql1="UPDATE ip_tab set ip_tab.ip='{}',`code`=0 WHERE devices = '{}'".format(i,j)
            sql2 = "SELECT `code` FROM ip_tab WHERE devices='{}'".format(j)
            sql_code=db.selectDb(sql2)
            if sql_code[1][0][0] == 2:
                logging.warning('设备测试完成，code={},devcies={}'.format(sql_code[1][0][0],j))
                continue
            else:
                db.updateDb(sql1)
                logging.warning('设备id：%s,更新ip完成,对应ip为：%s' % (j, i))
    except:
        logging.error('ip更新错误，设备状态=1,即为停止状态，对应设备id={},设备状态={}'.format(j,sql_code[1][0][0]))

    return ip_list



